#pragma one

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <memory>
#include <functional>

#include "Logger.hpp"
#include "Dictionary.hpp"

static const int sockfdDefault = -1;

using callback_t = std::function<std::string(std::string& word, const std::string &whoip, uint16_t whoport)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, callback_t cb)
        :_port(port)
        ,_is_running(false)
        ,_sockfd(sockfdDefault)
        ,_cb(cb)
    {}

    void Init()
    {
        //1、创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);//前两个参数已经能够表明我们创建的是udp套接字了，所以第三个参数传0即可
        if(_sockfd < 0)
        {
            LOG(Loglevel::FATAL) << "create socket error";
            exit(1);
        }
        LOG(Loglevel::INFO) << "create socket success : " << _sockfd;

        //2、填充sockaddr_in结构体（套接字是以结构体的形式进行保存和管理的）
        struct sockaddr_in local;
        bzero(&local, sizeof(local));//清空，以后我们一般使用memset清空
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = htonl(INADDR_ANY);//htonl:host to network long,将32位长整型数从主机字节序转换为网络字节序
        //字节序就是我们说的大端小端，网络中要求大端，所以此函数也会转换大小端
        //INADDR_ANY：0.0.0.0，他的含义被规定为了本主机的所有ip，也就是只要是发给这台主机的ip（不管是哪个ip）该主机都能收到
        local.sin_port = htons(_port);//htons:host to network short
        

        //3、使用bind将套接字与服务端进行绑定
        int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(Loglevel::FATAL) << "bind socket error";
            exit(2);
        }
        LOG(Loglevel::INFO) << "bind socket success : " << _sockfd;
    }

    void Start()
    {
        _is_running = true;
        while(true)
        {
            struct sockaddr_in peer;
            char buffer[1024];
            buffer[0] = 0;//清空字符数组
            socklen_t peerlen = sizeof(peer);
            //获取收到的信息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer), 0, (struct sockaddr*)&peer, &peerlen);
            
            if(n > 0)
            {
                std::string clientip = inet_ntoa(peer.sin_addr);//网络转主机并改uint32_t类型为string，当然也可以把两步拆开写
                //但是这样不用传参peer.sin_addr.s_addr
                uint16_t clientport = ntohs(peer.sin_port);
                buffer[n] = 0;//传过来的字符串没有\0，加上
                std::string word = buffer;
                LOG(Loglevel::DEBUG) << "用户查找: " << word;
                std::string result = _cb(word, clientip, clientport);
                ssize_t n = sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr*)&peer, peerlen);
            }
        }
        _is_running = false;
    }

    void Stop()
    {
        _is_running = false;
    }

    ~UdpServer()
    {}
    
private:
    int _sockfd;
    uint16_t _port;
    bool _is_running;
    callback_t _cb;
};
